package com.lanmaoly.web.server.controller;

import com.lanmaoly.web.server.entity.Result;
import com.lanmaoly.web.server.pojo.TbPayLog;
import com.lanmaoly.web.server.service.OrderService;
import com.lanmaoly.web.server.service.WeixinPayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Controller
@RequestMapping("/pay")
public class PayController {

    @Autowired
    private WeixinPayService weixinPayService;

    @Autowired
    private OrderService orderService;

    @RequestMapping("success")
    public String success(String payment, Model model) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String name = authentication.getName();
        if ("anonymousUser".equals(name)) {
            model.addAttribute("isLogin", false);
        } else {
            model.addAttribute("username", authentication.getName());
            model.addAttribute("isLogin", true);
        }
        model.addAttribute("payment", payment);
        return "portal/paysuccess";
    }

    @ResponseBody
    @RequestMapping("/createNative")
    public Map createNative() {
        //1.获取当前登录用户
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        //2.提取支付日志（从缓存 ）
        TbPayLog payLog = orderService.searchPayLogFromRedis(username);
        //3.调用微信支付接口
        if (payLog != null) {
            return weixinPayService.createNative(payLog.getOutTradeNo(), payLog.getTotalFee() + "");
        } else {
            return new HashMap<>();
        }
    }

    @ResponseBody
    @RequestMapping("/queryPayStatus")
    public Result queryPayStatus(String out_trade_no) {
        Result result = null;
        int x = 0;
        while (true) {
            //调用查询
            Map<String, String> map = weixinPayService.queryPayStatus(out_trade_no);
            if (map == null) {
                result = new Result(false, "支付发生错误");
                break;
            }
            if ("SUCCESS".equals(map.get("trade_state"))) {
                //支付成功
                result = new Result(true, "支付成功");
                //修改订单状态
                orderService.updateOrderStatus(out_trade_no, map.get("transaction_id"));
                break;
            }
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                log.error(e.getMessage());
            }
            x++;
            if (x >= 10) {
                result = new Result(false, "二维码超时");
                break;
            }

        }
        return result;
    }


}
